package com.lyt.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lyt.bean.Paper;
import com.lyt.bean.PaperQuestion;
import com.lyt.bean.Question;
import com.lyt.bean.TitleContent;
import com.lyt.dao.PaperDao;
import com.lyt.dao.QuestionDao;
import com.lyt.util.BeanUtil;
import com.lyt.vo.ItemVo;
import com.lyt.vo.PaperVo;
import com.lyt.vo.QuestionVo;
import com.lyt.vo.QuestionsVo;
import org.apache.ibatis.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.server.ServerCloneException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import cn.hutool.core.util.RandomUtil;

/**
 * @Author: zjx
 * @Date: 2023/04/27/20:03
 * @Description:
 */
@Service
public class PaperService {
    @Autowired
    PaperDao paperDao;

    @Autowired
    QuestionDao questionDao;
   public PaperVo  getPaperById(Integer id){
       //id是用户的id
       Paper paper = paperDao.selectPaperByPaperId(id);
       System.out.println("打印一下查询到的paper "+ paper);
       PaperVo paperVo = new PaperVo();
       //转换为paperVo
       BeanUtil.beanConvert(paper,paperVo);
       System.out.println(paperVo);
       //根据paperId获取 试题
      List<PaperQuestion> paperQuestions = questionDao.getPaperQuestionById(id);
//       System.out.println("打印一下 paperQuestions"+paperQuestions);
       //获取所有小题
      List<QuestionVo> questionVos = new ArrayList<>();
      //获取所有的相关题目 并写入 item中
       for (PaperQuestion paperQuestion : paperQuestions) {
           Question question = questionDao.getQuestionById(paperQuestion.getQuestionId());
//           System.out.println("查询到的 问题"+ question);
            //将question转化为vo
          QuestionVo questionVo = new QuestionVo();
           BeanUtil.beanConvert(question,questionVo);
           List<ItemVo> items = (List<ItemVo>) JSON.parse(question.getContent());
           System.out.println("item转换情况："+items);
           questionVo.setItems(items);
           questionVos.add(questionVo);

       }
       System.out.println("转换好的 qvo："+questionVos);
       if(paperVo.getTitleItems()!=null){
           System.out.println("不为空");
       }

       //创建一个 大题list
       List<QuestionsVo> questionsVos = new ArrayList();
       System.out.println("查到的 content"+ paper.getTitleContent());
       //先去查有多少个大题
       List<TitleContent> titleContents = (List<TitleContent>)JSON.parseArray(paper.getTitleContent(),TitleContent.class);
//        输出一下转换后的 titleContent

//       JSONObject msgEncap = JSON.parseObject(paper.getTitleContent());
//       List<TitleContent> titleContents = JSON.parseArray(msgEncap.getString("msgList"), Record.class);
//

       System.out.println("json转换后的titleContent的长度"+titleContents.size());
       //       设置大题title
       for (TitleContent titleContent : titleContents) {
           System.out.println("遍历输出 titleName"+titleContent.getTitleName());
           QuestionsVo questionsVo = new QuestionsVo();
           questionsVo.setQuestionName(titleContent.getTitleName());
           questionsVo.setType(titleContent.getType());
           questionsVos.add(questionsVo);//将titleContent转为questionsVos
       }


       for (QuestionsVo questionsVo : questionsVos) {
           //把小题塞进大题里面
           List<QuestionVo> questionVo1 = new ArrayList<>();
//           for (int i=0 ; i<questionVos.size();i++){
//               QuestionVo questionVo = questionVos.get(i);
//               System.out.println(questionVo.toString());
//               if (questionsVo.getType() == 1 && (questionVo.getType() == 1 || questionVo.getType() == 2)) {
//                   questionVo1.add(questionVo);//一号大题
//               }
//               if (questionsVo.getType() == questionVo.getType()) {
//                   questionVo1.add(questionVo);//二号大题
//               }
//               if (questionsVo.getType() == questionVo.getType()) {
//                   questionVo1.add(questionVo);//三号大题
//               }
//           }
           for (QuestionVo questionVo : questionVos) {//会重复输入
                   System.out.println(questionVo.toString());
                   if (questionsVo.getType() == questionVo.getType()) {
                       questionVo1.add(questionVo);//
                   }
           }
           questionsVo.setQuestionItems(questionVo1);
//           for (QuestionVo questionVo : questionVos) {
//               //questionsVo是每一道大题  questionVo是大题里面的小题
//
//               questionsVo.getQuestionItems().add(questionVo);
//           }
       }
       for (QuestionsVo questionsVo :questionsVos) {
           System.out.println("输出一下 已经穿件好的大题列表" + questionsVo);
       }
//        最后把每一道大题塞进一张试卷里
        paperVo.setTitleItems(questionsVos);
        return paperVo;

    }

    //zjx 封装paper转为PaperVo
    private List<PaperVo> papersVos(List<Paper> papers){
        List<PaperVo> paperVos = new ArrayList<>();
        for (Paper paper : papers) {
            PaperVo paperVo = new PaperVo();
            BeanUtil.beanConvert(paper,paperVo);
            List<QuestionsVo> questionsVos = (List<QuestionsVo>) JSON.parse(paper.getTitleContent());//获取大题
            paperVo.setTitleItems(questionsVos);
            paperVos.add(paperVo);
            //将content转换
        }
        return paperVos;
    }

    //zjx 获取所有试卷
    public List<PaperVo> getAllPaper(){
        List<Paper> papers = paperDao.getAllPaper();
        return papersVos(papers);
    };

    //zjx 根据年级获取所有试卷
    public List<PaperVo> getAllByGradePaper(Integer grade){
        List<Paper> papers = paperDao.getAllByGradePaper(grade);
        return papersVos(papers);
    };

    //根据课程获取所有试卷
    public List<PaperVo> getAllByCoursePaper(int courseId){
        List<Paper> papers = paperDao.getAllByCoursePaper(courseId);
        return papersVos(papers);
    };

    public int updatePaper(Paper paper){
        return paperDao.updatePaper(paper);
    };//根据试卷编号更新试卷名字，年级

    public Paper selectPaperBypaperId(Integer paperId){
        return paperDao.selectPaperByPaperId(paperId);
    };//根据试卷编号查询试卷


    public int deletePaper(Integer paperId){
        return paperDao.deletePaper(paperId);
    };//根据试卷编号删除试卷

    public int addPaper(PaperVo paperVo){
        Paper paper = new Paper();
        BeanUtil.beanConvert(paperVo,paper);//将paperVo转为paper

        //先写paper表
        // TODO: 2023/5/2   还有很多逻辑需要处理 例如 one two three
        // TODO: 2023/5/4   完成 one two three 和 score逻辑
        //因为id是自增的 取数据库中最大id然后+1即可 ，但是这样处理存在并发风险
        int newId = paperDao.getPaperMaxId()+1;
        int one = 0;//记录选择题数量
        int two = 0;//记录判断题数量
        int three = 0;//记录问答题数量
        int score = 0;//记录试卷总分分数
        paper.setPaperId(newId); //这个是自增的
        paper.setStatus(0);//试卷状态初始化为0（zjx）

        //添加时间
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        System.out.println(formatter.format(date));
        paper.setTime(formatter.format(date));

        System.out.println("转换后的paper "+paper);
        //处理 titleContent
        List<TitleContent> titleContents = new ArrayList<>();

        //遍历所有的大题获取 name
        List<QuestionsVo> titleItems = paperVo.getTitleItems();
//        for (int i = 0; i < titleItems.size(); i++) {
//            QuestionsVo titleItem = titleItems.get(i);
//            TitleContent titleContent = new TitleContent();
//            titleContent.setTitleName(titleItem.getQuestionName());//大题名字
//            titleContent.setSort(i);//大题编号
//            titleContents.add(titleContent);
//        }
//        paperDao.addPaper(paper);//zjx

        int index = 0;

        //再写试卷  -- 题目关系表
        List<PaperQuestion > paperQuestions = new ArrayList<>();
        //建立 试卷 试题关系映射
        for (QuestionsVo titleItem : paperVo.getTitleItems()) {//遍历大题
            titleItem = titleItems.get(index);
            TitleContent titleContent = new TitleContent();
            titleContent.setTitleName(titleItem.getQuestionName());//大题名字
            titleContent.setSort(index);//大题编号
            index++;
            for (QuestionVo questionItem : titleItem.getQuestionItems()) {//遍历大题中的小题
                int questionId = questionItem.getQuestionId();//获取小题中的id
                PaperQuestion paperQuestion = new PaperQuestion();//创建一个试卷试题关联对象
                //设置paperId
                paperQuestion.setPaperId(paper.getPaperId());
//                设置questionId
                paperQuestion.setQuestionId(questionId);
                //zjx
                int type = questionDao.getQuestionById(questionId).getType();
                titleContent.setType(type);
                if (type == 1 || type == 2){
                    one++;
                }else if (type == 4){
                    two++;
                }else if (type == 3){
                    three++;
                }
                score = score + questionDao.getQuestionById(questionId).getScore();

                paperQuestions.add(paperQuestion);//添加关联
            }
            titleContents.add(titleContent);
        }

        String titleContentJson = JSON.toJSONString(titleContents);//转为json格式
        paper.setTitleContent(titleContentJson);

        //zjx
        paper.setOne(one);
        paper.setTwo(two);
        paper.setThree(three);
        paper.setScore(score);
        paperDao.addPaper(paper);



        System.out.println("打印一下 paperQuestion "+paperQuestions);
        for (PaperQuestion paperQuestion : paperQuestions) {

            paperDao.addPaperQuestion(paperQuestion);
        }

        return 1;
    };//创建试卷


    //自动添加大题封装，zjx 2023/5/5
    private void settitleContents(int paperquestionSize,List<TitleContent> titleContents,String TitleName,int Sort,int type){
        if (paperquestionSize > 0){
            TitleContent titleContent = new TitleContent();
            titleContent.setTitleName(TitleName);
            titleContent.setSort(Sort);
            titleContent.setType(type);
            titleContents.add(titleContent);
        }
    }

    //试卷和试题关联关系封装方法，zjx 2023/5/5
    private int getPaperQuestion(int questionSize,int paperquestionSize,List<Question> source,int paperId,List<PaperQuestion> paperQuestions){
        int score = 0;
        List<Integer> typeRandomList = getEleList(questionSize,paperquestionSize);
        for (Integer index : typeRandomList){
            Question question = source.get(index);//在各题目数组中取
            score  = score + question.getScore();
            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setPaperId(paperId);
            paperQuestion.setQuestionId(question.getQuestionId());
            paperQuestions.add(paperQuestion);
        }
        return score;
    }

    //不重复随机数，zjx 2023/5/5
    private List<Integer> getEleList(int sourceSize,int resultSize){
        List<Integer> list = CollUtil.newArrayList();
        for (int i = 0; i < sourceSize ;i++){
            list.add(i);
        }
        return  RandomUtil.randomEles(list,resultSize);
    }


    //zjx 2023/5/5 自动组卷
    public int addPaperAut(PaperVo paperVo){
        Paper paper = new Paper();
        BeanUtil.beanConvert(paperVo,paper);//将paperVo转为paper

        //因为id是自增的 取数据库中最大id然后+1即可 ，但是这样处理存在并发风险
        int newId = paperDao.getPaperMaxId()+1;
        int score = 0;//记录试卷总分分数
        paper.setPaperId(newId); //这个是自增的
        paper.setStatus(0);//试卷状态初始化为0

        //添加时间
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        System.out.println(formatter.format(date));
        paper.setTime(formatter.format(date));

        //首先根据课程编号获取所有试题
        List<Question> questions = questionDao.getAllByCourseQuestion(paper.getCourseId());
        //根据题目类型查询所有题目,将各类题目放入到数组中，重新排序
        //选择
        List<Question> type1list = questions.stream().filter(question -> question.getType().equals(1) || question.getType().equals(2)).collect(Collectors.toList());
        //判断
        List<Question> type2list = questions.stream().filter(question -> question.getType().equals(4)).collect(Collectors.toList());
        //问答
        List<Question> type3list = questions.stream().filter(question -> question.getType().equals(3)).collect(Collectors.toList());
        System.out.println("转换后的paper "+paper);

        if ( type1list.size() < paper.getOne()){
            System.out.println("选择题数量不足");
            return 2;
        }
        if ( type2list.size() < paper.getTwo()){
            System.out.println("判断题数量不足");
            return 3;
        }
        if ( type3list.size() < paper.getThree()){
            System.out.println("问答题数量不足");
            return 4;
        }

        List<PaperQuestion> paperQuestions = new ArrayList<>();//存放试卷和试题关系集合

        //开始自动组卷
        //从选择题中随机抽取指定数量的题目放入到paperQuestions集合,平且获取各大题分数
        int score1 = getPaperQuestion(type1list.size(),paper.getOne(),type1list,paper.getPaperId(),paperQuestions);
        //从判断题中随机抽取指定数量的题目放入到paperQuestions集合
        int score2 = getPaperQuestion(type2list.size(),paper.getTwo(),type2list,paper.getPaperId(),paperQuestions);
        //从问答题中随机抽取指定数量的题目放入到paperQuestions集合
        int score3 = getPaperQuestion(type3list.size(),paper.getThree(),type3list,paper.getPaperId(),paperQuestions);

        //总分
        score = score1 + score2 + score3;

        System.out.println("打印一下 paperQuestion "+paperQuestions);
        for (PaperQuestion paperQuestion : paperQuestions) {
            paperDao.addPaperQuestion(paperQuestion);//添加试卷试题关联关系
        }

        //处理 titleContent
        List<TitleContent> titleContents = new ArrayList<>();

        //如果选择题数量大于0，自动创建选择大题
        settitleContents(paper.getOne(),titleContents,"选择题",0,1);
        //如果判断题数量大于0，自动创建判断题大题
        settitleContents(paper.getTwo(),titleContents,"判断题",1,2);
        //如果问答题数量大于0，自动创建问答题大题
        settitleContents(paper.getThree(),titleContents,"问答题",2,3);

        String titleContentJson = JSON.toJSONString(titleContents);//转为json格式
        paper.setTitleContent(titleContentJson);

        paper.setScore(score);
        paperDao.addPaper(paper);

        return 1;
    };//自动创建试卷

    public int commitPaper(@Param("status")Integer status, @Param("paperId")Integer paperId){
        return paperDao.commitPaper(1,paperId);
    };//发布试卷
}
